import { PageEnum } from '@/enums/pageEnum';

import { useRouter } from 'vue-router';
import { REDIRECT_NAME } from '@/router/constant';

function handleError(e) {
	console.error(e);
}

/**
 * page switch
 */
export function useGo(_router) {
	const { push, replace } = _router || useRouter();
	function go(opt = PageEnum.BASE_HOME, isReplace = false) {
		if (!opt) {
			return;
		}
		isReplace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
	}
	return go;
}

/**
 * @description: 重做当前页面
 */
export const useRedo = (_router) => {
	const { replace, currentRoute } = _router || useRouter();
	const { query, params = {}, name, fullPath } = unref(currentRoute.value);
	function redo() {
		return new Promise((resolve) => {
			if (name === REDIRECT_NAME) {
				resolve(false);
				return;
			}
			if (name && Object.keys(params).length > 0) {
				params['_origin_params'] = JSON.stringify(params ?? {});
				params['_redirect_type'] = 'name';
				params['path'] = String(name);
			} else {
				params['_redirect_type'] = 'path';
				params['path'] = fullPath;
			}
			replace({ name: REDIRECT_NAME, params, query }).then(() => resolve(true));
		});
	}
	return redo;
};
